package network;

import java.net.*;
import static network.Communicator.*;

public class BroadcastListener extends Thread {

	InetAddress serverIP, myIP;
	int serverPort, myPort;
	DatagramSocket dataSocket;
	Communicator creater;
	boolean closed = false;
	private final int MAX_CHECK_CLOSE_TIME = 5000;
	
	public BroadcastListener(InetAddress serverIP, int serverPort, Communicator c) {
		this.serverIP = serverIP;
		this.serverPort = serverPort;
		creater = c;
		myPort = BROADCAST_PORT;
		try {
			myIP = InetAddress.getLocalHost();
			dataSocket = new MulticastSocket(myPort);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		System.out.println("boardcast start listening...");
		byte[] receiveD = new byte[50];
		DatagramPacket receiveP = new DatagramPacket(receiveD, receiveD.length);
		while (!closed) {
			try {
				dataSocket.setSoTimeout(MAX_CHECK_CLOSE_TIME);
				dataSocket.receive(receiveP);
				if (closed) break;
			} catch (SocketTimeoutException e) {
				if (closed) break;
				continue;
			} catch (Exception e) {
				e.printStackTrace();
			}
			checkTarget(receiveP.getData(), receiveP.getLength());
		}
		dataSocket.close();
	}
	
	public void close() {
		closed = true;
	}

	boolean checkTarget(byte[] byteval, int len) {
		String info = new String(byteval);
		info = info.substring(0, len);
		if (len > 50) return false;
		if (!info.endsWith("#")) return false;
		String[] splitS = info.split(" ");
		if (splitS.length != 5) return false;
		try {
			if (!serverIP.getHostAddress().equals(splitS[0])
					|| !(serverPort == Integer.parseInt(splitS[1])))
				return false;
		} catch (Exception e) {
			return false;
		}
		creater.connectTo(splitS[2], Integer.parseInt(splitS[3]));
		return true;
	}


}
